import { Checkbox, Form, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { Link, history, useModel } from 'umi';
import { getPageQuery } from '@/utils/utils';
import logo from '@/assets/login-logo.png';
import bg from '@/assets/bg.png';
import { LoginParamsType, fakeAccountLogin } from '@/services/login';
import LoginFrom from './components/Login';
import styles from './style.less';
import IconFont from '@/components/IconFont';
import Secret from '@/utils/secret';
import classnames from 'classnames';

const { Username, Password, Submit } = LoginFrom;

/**
 * 此方法会跳转到 redirect 参数所在的位置
 */
const replaceGoto = () => {
  const urlParams = new URL(window.location.href);
  const params = getPageQuery();
  let { redirect } = params as { redirect: string };
  if (redirect) {
    const redirectUrlParams = new URL(redirect);
    if (redirectUrlParams.origin === urlParams.origin) {
      redirect = redirect.substr(urlParams.origin.length);
      if (redirect.match(/^\/.*#/)) {
        redirect = redirect.substr(redirect.indexOf('#') + 1);
      }
    } else {
      window.location.href = '/';
      return;
    }
  }
  history.replace(redirect || '/');
};

const Login: React.FC<{}> = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginStateType>({});
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();
  useEffect(() => {
    const loginInfo = localStorage.getItem('loginInfo');
    let params = loginInfo && JSON.parse(Secret.Decrypt(loginInfo));

    params &&
      form.setFieldsValue({
        userName: params.userName,
        passWord: params.passWord,
      });
  }, []);

  const { refresh } = useModel('@@initialState');
  const [autoLogin, setAutoLogin] = useState(localStorage.getItem('loginInfo') ? true : false);
  const [type, setType] = useState<string>('account');

  const handleSubmit = async (values: LoginParamsType) => {
    setSubmitting(true);
    try {
      const params = { ...values, verificationCode: 'zhh' };

      const secretstring = Secret.Encrypt(JSON.stringify(params));
      // 登录
      const msg = await fakeAccountLogin(secretstring);
      if (msg.result === 0) {
        message.success('登录成功！');

        if (autoLogin) {
          localStorage.setItem('loginInfo', secretstring);
        } else {
          localStorage.removeItem('loginInfo');
        }
        //把token保存到浏览器内存里
        msg.data && localStorage.setItem('token', msg.data.token as string);
        msg.data && localStorage.setItem('webSocket', msg.data.webSocket as string);
        //跳转
        replaceGoto();
        //更新初始值
        setTimeout(() => {
          refresh();
        }, 0);
        // 设置成功恢复初始值
        JSON.stringify(userLoginState) !== '{}' && setUserLoginState({});
        return;
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      message.error('登录失败，请重试！');
    }
    setSubmitting(false);
  };

  const { msg: errorMsg } = userLoginState;

  return (
    <div className={styles.container}>
      {/* <div className={styles.lang}>
        <SelectLang />
      </div> */}
      <div className={styles.imageWrap}>
        <img alt="" className={styles.bg} src={bg} />
      </div>
      <div className={styles.content}>
        <div className={styles.center}>
          <div className={styles.top}>
            <div className={styles.header}>
              <Link to="/user/login">
                <img alt="logo" className={styles.logo} src={logo} />
              </Link>
            </div>
          </div>
          <div className={classnames(styles.status, errorMsg && styles.error)}>
            <span>{errorMsg ? errorMsg : 'Login with your account!'}</span>
          </div>

          <div className={styles.main}>
            <LoginFrom activeKey={type} form={form} onTabChange={setType} onSubmit={handleSubmit}>
              <Username
                name="userName"
                placeholder="请输入用户名"
                prefix={<IconFont type={'iconyonghuming'} />}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <Password
                name="passWord"
                placeholder="请输入用户名"
                prefix={<IconFont type={'iconmima'} />}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <div>
                <Checkbox checked={autoLogin} onChange={(e) => setAutoLogin(e.target.checked)}>
                  记住密码
                </Checkbox>
              </div>
              <Submit loading={submitting}>登录</Submit>
            </LoginFrom>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
